package concurrence;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock demo
 */
public class ConcurrentDemo {
    private static ReentrantLock lock = new ReentrantLock();

    private static ExecutorService executor = Executors.newCachedThreadPool();

    private static CountDownLatch countDownLatch = new CountDownLatch(100);

    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
//        Bank bank = new Bank();
//        final CountDownLatch latch = new CountDownLatch(100);
//        for (int i = 1; i <= 1000; i++) {
//            executor.execute(new MybanRunnable(bank, latch));
//        }
//
//        try {
//            latch.await();
//            System.out.println("main" + bank.account);
//        } catch (Exception e) {
//            System.out.println("main error" + bank.account);
//
//            e.printStackTrace();
//        }
        Callable ca1 = new Callable(){

            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "凉菜准备完毕";
            }
        };
        FutureTask<String> ft1 = new FutureTask<String>(ca1);
        new Thread(ft1).start();

    }


    private static class MybanRunnable implements Runnable {

        private Bank bank;

        private CountDownLatch latch;

        public MybanRunnable(Bank bank, CountDownLatch latch) {
            this.bank = bank;
            this.latch = latch;
        }

        @Override
        public void run() {
//            for (int i = 0; i < 10; i++) {
//                bank.save1(100);
//                System.out.println("账户余额是---" + bank.getAccount());
//            }
            bank.save(100);
//            System.out.println(Thread.currentThread().getName() + ", 账户余额是---" + bank.getAccount());
            latch.countDown();
        }
    }

    private static class Bank {

        private volatile int account = 0;

        public int getAccount() {
            return account;
        }

        //同步方法
        public void save(int money) {
            account += money;
        }

        public void save1(int money) {
            //同步代码块
            synchronized (this) {
                account += money;
            }
        }
    }
}
